<?php
	include('tex_functions.php');
	if (!isset($_POST['nazwa'])){
		include('choose_categories.php');
	}
	else{
		$filename = "data/pdf/".$_POST['nazwa'].".tex";
		
		$content = genHeader($_POST['nazwa']);
		
		foreach ( $_POST['chosen'] as $category )
		{
			$gianttable = get_all_sections();
			$category_level = -1;
			$category_name = "";
			foreach( $gianttable as $wpis ) // awfully excessive n^2 ;)
			{
				if ( $wpis[2] == $category )
				{
					$category_level = $wpis[1];
					$category_name = $wpis[0];
				}
			}
			$content .= genCategory($category_name, $category_level-1);
			$problems = get_section_problems( $category );
			foreach ( $problems as $problem )
			{
				$problem_name = get_problem_name($problem);
				$problem_description = get_problem_description($problem);
				$content .= genProblem($problem_name, $problem_description, $category_level);
				$solutions = get_problem_solutions( $problem );
				foreach ( $solutions as $solution )
				{
					if ( get_solution_status( $solution ) == "ACCEPTED" )
					{
						$code = load_file( "data/solutions/$solution.cpp" );
						$content .= genSolution($code);
					}
				}
				$content .= "\\pagebreak
				";
			}
		}
		
		$content .= genFooter();

		save_file($filename,$content);
		
		// to jest trzy razy specjalnie ;). To ciekawe, ale latex dobrze generuje spis tresci tylko, jesli obrabia ten sam plik 2-3 razy pod rzad ;)
		exec("pdflatex -interaction=nonstopmode -output-directory data/pdf '".$filename."' ");
		exec("pdflatex -interaction=nonstopmode -output-directory data/pdf '".$filename."' ");
		exec("pdflatex -interaction=nonstopmode -output-directory data/pdf '".$filename."' ");
		
		echo "<center><h1 class=\"postTitle\"> <a href=\"data/pdf/".$_POST['nazwa'].".pdf\"> Pobierz dokument </a></h1>";
		
	}

?>
